﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MINERP.DAL;
using MINERP.COM;
using MINERP.DAL.CommonDAL;
using MINERP.MODEL.FoundationModel;
using MINERP.BLL.CustomerManage;
using System.Data;
using FastReport;
using System.Windows.Forms;

namespace MINERP.BLL.Common
{
    public static class PrintOrdersToBill
    {
        public static SHOP_Bill_Info OrganizationBillData(List<int> ListOrderProductId, int inShopId)
        {
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {
                if (dataBase.Connection.State != System.Data.ConnectionState.Open)
                {
                    dataBase.Connection.Open();
                }
                System.Data.Common.DbTransaction tran = dataBase.Connection.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);
                SHOP_Bill sb = new SHOP_Bill();                     //用于写入数据库
                SHOP_Bill_Info sbinfo = new SHOP_Bill_Info();       //用于返回给打印页面使用
                List<int> DonedOrderProudctId = new List<int>(ListOrderProductId);//能够正常结帐单的产品ID
                //ListOrderProductId=ListOrderProductId.OrderBy(p=>p)
                //初始信息
                double Bill_Price = 0;
                bool hasForcibePrint = true;
                sb.NeedDeliver = 1;                                 //是否需要配送   
                sb.Status = (int)ShopBillStatus.UnCheckOut;

                sb.CreateTime = CommonMethodDAL.GetServerTime();//获取系统时间
                sbinfo.CreateTime = sb.CreateTime;//获取系统时间
                int Bill_Detail_Id = 1;                             //用于报表中的关联ID，与数据库实际的ID并不一样

                sbinfo.List_Detail = new List<Bill_Detail_Info>();

                Shop curShop = dataBase.Shop.FirstOrDefault(p => p.ShopId == inShopId);

                #region 得到商户的帐单的顺序号

                List<SHOP_Bill> listShopBill = dataBase.SHOP_Bill.Where(s => s.CreateTime.Month == sb.CreateTime.Month && s.CreateTime.Year == sb.CreateTime.Year && s.Shop.ShopId == inShopId).ToList();
                if (listShopBill.Count <= 0)
                {
                    sb.BillOrderCode = 1;
                }
                else
                {
                    sb.BillOrderCode = listShopBill.Max(p => p.BillOrderCode) + 1;
                }


                //sb.BillOrderCode = dataBase.SHOP_Bill.Where(s => s.CreateTime.Month == DateTime.Now.Month && s.Shop.ShopId == shopId).Max(a => a.BillOrderCode) + 1;

                sbinfo.BillOrderCode = sb.BillOrderCode;




                #endregion


                sbinfo.BillOrderCode = sb.BillOrderCode;
                foreach (var orderProductId in ListOrderProductId)
                {



                    decimal orderInfoPrice = 0;//此产品的真实价格

                    orderInfo oi = dataBase.orderInfo.Include("photoInfo").FirstOrDefault(p => p.OrderProductId == orderProductId);

                    if (oi.status == (int)OrderInfoStatus.Completed)
                    {
                        dataBase.Refresh(System.Data.Objects.RefreshMode.StoreWins, oi);
                    }

                    #region 加载数据库
                    if (!oi.Tb_ProductReference.IsLoaded)
                    {
                        oi.Tb_ProductReference.Load();
                    }
                    if (!oi.Tb_Product.tb_CostTypeReference.IsLoaded)
                    {
                        oi.Tb_Product.tb_CostTypeReference.Load();
                    }
                    if (!oi.Tb_Product.Tb_PorductCategoryReference.IsLoaded)
                    {
                        oi.Tb_Product.Tb_PorductCategoryReference.Load();
                    }
                    if (!curShop.Shop_Product_Price.IsLoaded)
                    {
                        curShop.Shop_Product_Price.Load();
                    }
                    if (!oi.photoInfo.IsLoaded)
                    {
                        oi.photoInfo.Load();
                    }
                    if (!oi.Tb_OrderBagReference.IsLoaded)
                    {
                        oi.Tb_OrderBagReference.Load();
                    }
                    string orderBagName = oi.Tb_OrderBag.BagName.Split('_')[0];

                    #endregion

                    Bill_Detail bd = new Bill_Detail() { OiRemark = oi.Remark, OrderInfoCode = oi.OrderProductCode, OrderProductName = oi.OrderProductName, CtmName = oi.CtmName, IsCheckOut = false };
                    Bill_Detail_Info dbinfo = new Bill_Detail_Info() { BillDetailId = Bill_Detail_Id, Remark = oi.Remark, OrderInfoCode = oi.OrderProductId.ToString(), OrderProductName = oi.OrderProductName, CtmName = oi.CtmName, OrderBagName = orderBagName };
                    Bill_Detail_Id++;
                    dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();



                    orderInfoPrice = BillBLL.GetOrderPrice(curShop, oi, dataBase, bd);

                    ConvertOrderDetailaToViewModel(bd, curShop, dbinfo);


                    #region 如果产品满足财务信息，则可以找印帐单，并判断登陆者的权限在“在余额不足”情况下是否可以打帐单

                    #region //对帐户金额的操作
                    ShopBlanceCrushRecord br;
                    switch (curShop.CheckOutType)
                    {
                        case 0://预付款用户
                        case 2://现结用户
                        case 5://先结
                            #region


                            curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                            if (curShop.OrderBalance < 0)
                            {
                                curShop.OrderBalance = 0;
                            }


                            if (curShop.Balance < (decimal)orderInfoPrice)
                            {
                                //如果余额不足，就判断是否有权限可打印此帐单
                                if (hasForcibePrint)//可以强打
                                {
                                    sb.Status = (int)ShopBillStatus.UnCheckOut;
                                    curShop.Balance -= (decimal)orderInfoPrice;
                                    //向商户帐户记录表添加记录
                                    br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                    dataBase.AddToShopBlanceCrushRecord(br);
                                }
                                else
                                {
                                    oi.status = (int)OrderInfoStatus.WaitPay;
                                    curShop.OrderBalance += oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;

                                    DonedOrderProudctId.Remove(oi.OrderProductId);
                                }
                            }
                            else
                            {

                                bd.IsCheckOut = true;
                                curShop.Balance -= (decimal)orderInfoPrice;

                                //向商户帐户记录表添加记录
                                br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                dataBase.AddToShopBlanceCrushRecord(br);
                            }

                            //检查是否需要报警
                            if (curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                            {
                                BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);
                            }
                            #endregion
                            break;
                        case 1://信用额度用户
                        case 3://结帐日用户
                        case 4://结单日与信用额度用户
                        case 6://代收款
                            #region
                            curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                            if (curShop.OrderBalance < 0)
                            {
                                curShop.OrderBalance = 0;
                            }
                            curShop.Balance -= (decimal)orderInfoPrice;

                            if (curShop.CheckOutType == 1)//信用额度用户
                            {
                                if (curShop.CreditLimit + curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                {
                                    BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);

                                }
                            }
                            else
                            {
                                int days = new DateTime(sb.CreateTime.Year, sb.CreateTime.Month, (int)curShop.OverDay).Subtract(sb.CreateTime).Days;
                                if (days > 0 && days < curShop.AlarmDays)
                                {
                                    BillBLL.InsertAccountAlarmMsg("距结帐日小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);
                                }
                            }

                            //向商户帐户记录表添加记录
                            br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                            dataBase.AddToShopBlanceCrushRecord(br);
                            sb.Status = (int)ShopBillStatus.UnCheckOut;
                            #endregion
                            break;
                        default:
                            break;
                    }

                    #endregion
                    sb.Bill_Detail.Add(bd);

                    dbinfo.BillDetailId = Bill_Detail_Id;
                    sbinfo.List_Detail.Add(dbinfo);
                    Bill_Detail_Id++;
                    Bill_Price += (double)orderInfoPrice;
                    oi.isCount = (int)orderinfoPerBill.UnPrint;//0为
                    dataBase.SaveChanges();
                    #endregion


                    //return sbinfo;


                }

                //记录帐单信息          
                sb.Shop = curShop;
                sb.TotalPrice = (decimal)Math.Round(Bill_Price, 4, MidpointRounding.ToEven);
                sbinfo.Shop = new Shop_Info() { Address = curShop.address, ShopId = curShop.ShopId, ShopKeeper = curShop.shopKeeper, ShopName = curShop.shopName, Tel1 = curShop.Tel1, Tel2 = curShop.Tel2, QQ = curShop.QQ, IsNeedPrintUPrice = curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice, Salesman = curShop.Salesman, CreditLevel = curShop.CreditLevel == null ? 0 : (int)curShop.CreditLevel, IsAssignByCustom = curShop.IsAssignByCustom };
                sbinfo.ShopBalance = (double)curShop.Balance;//指商户的总共欠款额度(包括本帐单)

                //sbinfo.BillCount = Bill_Price;
                sbinfo.BillCount = Math.Round(Bill_Price, 4, MidpointRounding.ToEven);
                if (sb.Bill_Detail.Count(a => a.OrderInfoCode != "0") > 0)
                {
                    if (sb.Bill_Detail.Count(b => !b.IsCheckOut) > 0)
                    {
                        sb.Status = (int)ShopBillStatus.UnCheckOut;
                    }
                    else
                    {
                        sb.Status = (int)ShopBillStatus.CheckedOut;
                    }
                    sb.ShopBalance = curShop.Balance ?? 0;
                    dataBase.AddToSHOP_Bill(sb);

                    dataBase.SaveChanges();
                    tran.Commit();
                }
                else
                {
                    sbinfo = null;
                    sb = null;
                    tran.Rollback();
                }
                if (sbinfo != null)
                {
                    sbinfo.BillId = sb.BillId;
                    sbinfo.List_Detail = sbinfo.List_Detail.OrderBy(ld => ld.CtmName).ToList();//按客户名称排个序                       
                }
                return sbinfo;
            }
        }
        public static SHOP_Bill_Info OrganizationBillData(int OrderBagID)
        {
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {
                if (dataBase.Connection.State != System.Data.ConnectionState.Open)
                {
                    dataBase.Connection.Open();
                }
                System.Data.Common.DbTransaction tran = dataBase.Connection.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);
                SHOP_Bill sb = new SHOP_Bill();                     //用于写入数据库
                SHOP_Bill_Info sbinfo = new SHOP_Bill_Info();       //用于返回给打印页面使用
                sbinfo.Result = 0;
                Tb_OrderBag orderbag = dataBase.Tb_OrderBag.FirstOrDefault(b => b.OrderBagId == OrderBagID);
                if (orderbag == null)
                {
                    sbinfo.Result = -1;//订单不存在
                    return sbinfo;
                }
                orderbag.ShopReference.Load();
                orderbag.orderInfo.Load();
                Shop curShop = orderbag.Shop;
                List<orderInfo> orderList = orderbag.orderInfo.Where(o => o.isCount == 0 || o.isCount == null).ToList();
                if (orderList.Count == 0)
                {
                    sbinfo.Result = -2;//已经打过结账单重新打的话 财务那里
                    return sbinfo;
                }
                List<int> DonedOrderProudctId = new List<int>(orderList.Count);//能够正常结帐单的产品ID
                //ListOrderProductId=ListOrderProductId.OrderBy(p=>p)
                //初始信息
                double Bill_Price = 0;
                bool hasForcibePrint = true;
                sb.NeedDeliver = 1;                                 //是否需要配送   
                sb.Status = (int)ShopBillStatus.UnCheckOut;

                sb.CreateTime = CommonMethodDAL.GetServerTime();//获取系统时间
                sbinfo.CreateTime = sb.CreateTime;//获取系统时间
                int Bill_Detail_Id = 1;                             //用于报表中的关联ID，与数据库实际的ID并不一样

                sbinfo.List_Detail = new List<Bill_Detail_Info>();



                #region 得到商户的帐单的顺序号

                List<SHOP_Bill> listShopBill = dataBase.SHOP_Bill.Where(s => s.CreateTime.Month == sb.CreateTime.Month && s.CreateTime.Year == sb.CreateTime.Year && s.Shop.ShopId == curShop.ShopId).ToList();
                if (listShopBill.Count <= 0)
                {
                    sb.BillOrderCode = 1;
                }
                else
                {
                    sb.BillOrderCode = listShopBill.Max(p => p.BillOrderCode) + 1;
                }


                //sb.BillOrderCode = dataBase.SHOP_Bill.Where(s => s.CreateTime.Month == DateTime.Now.Month && s.Shop.ShopId == shopId).Max(a => a.BillOrderCode) + 1;

                sbinfo.BillOrderCode = sb.BillOrderCode;




                #endregion


                sbinfo.BillOrderCode = sb.BillOrderCode;
                foreach (orderInfo oi in orderList)
                {



                    decimal orderInfoPrice = 0;//此产品的真实价格

                    //orderInfo oi = dataBase.orderInfo.Include("photoInfo").FirstOrDefault(p => p.OrderProductId == orderProductId);

                    oi.photoInfo.Load();

                    #region 加载数据库
                    if (!oi.Tb_ProductReference.IsLoaded)
                    {
                        oi.Tb_ProductReference.Load();
                    }
                    if (!oi.Tb_Product.tb_CostTypeReference.IsLoaded)
                    {
                        oi.Tb_Product.tb_CostTypeReference.Load();
                    }
                    if (!oi.Tb_Product.Tb_PorductCategoryReference.IsLoaded)
                    {
                        oi.Tb_Product.Tb_PorductCategoryReference.Load();
                    }
                    if (!curShop.Shop_Product_Price.IsLoaded)
                    {
                        curShop.Shop_Product_Price.Load();
                    }
                    if (!oi.photoInfo.IsLoaded)
                    {
                        oi.photoInfo.Load();
                    }
                    if (!oi.Tb_OrderBagReference.IsLoaded)
                    {
                        oi.Tb_OrderBagReference.Load();
                    }
                    if (!oi.WorkOrderFlowList.IsLoaded)
                    {
                        oi.WorkOrderFlowList.Load();
                        oi.WorkOrderFlowList.ToList().ForEach(w => w.tb_TechReference.Load());
                    }
                    if (oi.WorkOrderFlowList.FirstOrDefault(w => w.tb_Tech.TechType == 4) != null)
                    {
                        continue;
                    }
                    string orderBagName = oi.Tb_OrderBag.BagName.Split('_')[0];

                    #endregion

                    Bill_Detail bd = new Bill_Detail() { OiRemark = oi.Remark, OrderInfoCode = oi.OrderProductCode, OrderProductName = oi.OrderProductName, CtmName = oi.CtmName, IsCheckOut = false };
                    Bill_Detail_Info dbinfo = new Bill_Detail_Info() { BillDetailId = Bill_Detail_Id, Remark = oi.Remark, OrderInfoCode = oi.OrderProductId.ToString(), OrderProductName = oi.OrderProductName, CtmName = oi.CtmName, OrderBagName = orderBagName };
                    Bill_Detail_Id++;
                    dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();



                    orderInfoPrice = BillBLL.GetOrderPrice(curShop, oi, dataBase, bd);

                    ConvertOrderDetailaToViewModel(bd, curShop, dbinfo);


                    #region 如果产品满足财务信息，则可以找印帐单，并判断登陆者的权限在“在余额不足”情况下是否可以打帐单

                    #region //对帐户金额的操作
                    ShopBlanceCrushRecord br;
                    switch (curShop.CheckOutType)
                    {
                        case 0://预付款用户
                        case 2://现结用户
                        case 5://先结
                            #region


                            curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                            if (curShop.OrderBalance < 0)
                            {
                                curShop.OrderBalance = 0;
                            }


                            if (curShop.Balance < (decimal)orderInfoPrice)
                            {
                                //如果余额不足，就判断是否有权限可打印此帐单
                                if (hasForcibePrint)//可以强打
                                {
                                    sb.Status = (int)ShopBillStatus.UnCheckOut;
                                    curShop.Balance -= (decimal)orderInfoPrice;
                                    //向商户帐户记录表添加记录
                                    br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                    dataBase.AddToShopBlanceCrushRecord(br);
                                }
                                else
                                {
                                    oi.status = (int)OrderInfoStatus.WaitPay;
                                    curShop.OrderBalance += oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;

                                    DonedOrderProudctId.Remove(oi.OrderProductId);
                                }
                            }
                            else
                            {

                                bd.IsCheckOut = true;
                                curShop.Balance -= (decimal)orderInfoPrice;

                                //向商户帐户记录表添加记录
                                br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                dataBase.AddToShopBlanceCrushRecord(br);
                            }

                            //检查是否需要报警
                            if (curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                            {
                                BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);
                            }
                            #endregion
                            break;
                        case 1://信用额度用户
                        case 3://结帐日用户
                        case 4://结单日与信用额度用户
                        case 6://代收款
                            #region
                            curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                            if (curShop.OrderBalance < 0)
                            {
                                curShop.OrderBalance = 0;
                            }
                            curShop.Balance -= (decimal)orderInfoPrice;

                            if (curShop.CheckOutType == 1)//信用额度用户
                            {
                                if (curShop.CreditLimit + curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                {
                                    BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);

                                }
                            }
                            else
                            {
                                int days = new DateTime(sb.CreateTime.Year, sb.CreateTime.Month, (int)curShop.OverDay).Subtract(sb.CreateTime).Days;
                                if (days > 0 && days < curShop.AlarmDays)
                                {
                                    BillBLL.InsertAccountAlarmMsg("距结帐日小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);
                                }
                            }

                            //向商户帐户记录表添加记录
                            br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                            dataBase.AddToShopBlanceCrushRecord(br);
                            sb.Status = (int)ShopBillStatus.UnCheckOut;
                            #endregion
                            break;
                        default:
                            break;
                    }

                    #endregion
                    sb.Bill_Detail.Add(bd);

                    dbinfo.BillDetailId = Bill_Detail_Id;
                    sbinfo.List_Detail.Add(dbinfo);
                    Bill_Detail_Id++;
                    Bill_Price += (double)orderInfoPrice;
                    oi.isCount = (int)orderinfoPerBill.Printed;//0为
                    dataBase.SaveChanges();
                    #endregion


                    //return sbinfo;


                }

                //记录帐单信息          
                sb.Shop = curShop;
                sb.TotalPrice = (decimal)Math.Round(Bill_Price, 4, MidpointRounding.ToEven);
                sbinfo.Shop = new Shop_Info() { Address = curShop.address, ShopId = curShop.ShopId, ShopKeeper = curShop.shopKeeper, ShopName = curShop.shopName, Tel1 = curShop.Tel1, Tel2 = curShop.Tel2, QQ = curShop.QQ, IsNeedPrintUPrice = curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice, Salesman = curShop.Salesman, CreditLevel = curShop.CreditLevel == null ? 0 : (int)curShop.CreditLevel, IsAssignByCustom = curShop.IsAssignByCustom };
                sbinfo.ShopBalance = (double)curShop.Balance;//指商户的总共欠款额度(包括本帐单)

                //sbinfo.BillCount = Bill_Price;
                sbinfo.BillCount = Math.Round(Bill_Price, 4, MidpointRounding.ToEven);
                if (sb.Bill_Detail.Count(a => a.OrderInfoCode != "0") > 0)
                {
                    if (sb.Bill_Detail.Count(b => !b.IsCheckOut) > 0)
                    {
                        sb.Status = (int)ShopBillStatus.UnCheckOut;
                    }
                    else
                    {
                        sb.Status = (int)ShopBillStatus.CheckedOut;
                    }
                    sb.ShopBalance = curShop.Balance ?? 0;
                    dataBase.AddToSHOP_Bill(sb);

                    dataBase.SaveChanges();
                    tran.Commit();
                }
                else
                {
                    sbinfo = null;
                    sb = null;
                    tran.Rollback();
                }
                if (sbinfo != null)
                {
                    sbinfo.BillId = sb.BillId;
                    sbinfo.List_Detail = sbinfo.List_Detail.OrderBy(ld => ld.CtmName).ToList();//按客户名称排个序                       
                }
                return sbinfo;
            }
        }
        public static List<SHOP_Bill_Info> OrganizationBillDataList(int OrderBagID)
        {
            List<SHOP_Bill_Info> rtnList = new List<SHOP_Bill_Info>();
            using (newSampleYPDBEntities dataBase = new newSampleYPDBEntities())
            {
                if (dataBase.Connection.State != System.Data.ConnectionState.Open)
                {
                    dataBase.Connection.Open();
                }
                System.Data.Common.DbTransaction tran = dataBase.Connection.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);
                try
                {
                    Tb_OrderBag orderbag = dataBase.Tb_OrderBag.FirstOrDefault(b => b.OrderBagId == OrderBagID);
                    if (orderbag == null)
                    {

                        return rtnList;
                    }
                    orderbag.ShopReference.Load();
                    orderbag.orderInfo.Load();
                    Shop curShop = orderbag.Shop;
                    List<orderInfo> orderList = orderbag.orderInfo.Where(o => o.isCount == 0 || o.isCount == null).ToList();
                    if (orderList.Count == 0)
                    {

                        return rtnList;
                    }


                    foreach (orderInfo oi in orderList)
                    {
                        SHOP_Bill sb = new SHOP_Bill();                     //用于写入数据库
                        SHOP_Bill_Info sbinfo = new SHOP_Bill_Info();       //用于返回给打印页面使用

                        List<int> DonedOrderProudctId = new List<int>(orderList.Count);//能够正常结帐单的产品ID
                        //ListOrderProductId=ListOrderProductId.OrderBy(p=>p)
                        //初始信息
                        double Bill_Price = 0;
                        bool hasForcibePrint = true;
                        sb.NeedDeliver = 1;                                 //是否需要配送   
                        sb.Status = (int)ShopBillStatus.UnCheckOut;

                        sb.CreateTime = CommonMethodDAL.GetServerTime();//获取系统时间
                        sbinfo.CreateTime = sb.CreateTime;//获取系统时间
                        int Bill_Detail_Id = 1;                             //用于报表中的关联ID，与数据库实际的ID并不一样

                        sbinfo.List_Detail = new List<Bill_Detail_Info>();



                        #region 得到商户的帐单的顺序号

                        List<SHOP_Bill> listShopBill = dataBase.SHOP_Bill.Where(s => s.CreateTime.Month == sb.CreateTime.Month && s.CreateTime.Year == sb.CreateTime.Year && s.Shop.ShopId == curShop.ShopId).ToList();
                        if (listShopBill.Count <= 0)
                        {
                            sb.BillOrderCode = 1;
                        }
                        else
                        {
                            sb.BillOrderCode = listShopBill.Max(p => p.BillOrderCode) + 1;
                        }


                        //sb.BillOrderCode = dataBase.SHOP_Bill.Where(s => s.CreateTime.Month == DateTime.Now.Month && s.Shop.ShopId == shopId).Max(a => a.BillOrderCode) + 1;

                        sbinfo.BillOrderCode = sb.BillOrderCode;




                        #endregion


                        sbinfo.BillOrderCode = sb.BillOrderCode;


                        decimal orderInfoPrice = 0;//此产品的真实价格

                        //orderInfo oi = dataBase.orderInfo.Include("photoInfo").FirstOrDefault(p => p.OrderProductId == orderProductId);

                        oi.photoInfo.Load();

                        #region 加载数据库
                        if (!oi.Tb_ProductReference.IsLoaded)
                        {
                            oi.Tb_ProductReference.Load();
                        }
                        if (!oi.Tb_Product.tb_CostTypeReference.IsLoaded)
                        {
                            oi.Tb_Product.tb_CostTypeReference.Load();
                        }
                        if (!oi.Tb_Product.Tb_PorductCategoryReference.IsLoaded)
                        {
                            oi.Tb_Product.Tb_PorductCategoryReference.Load();
                        }
                        if (!curShop.Shop_Product_Price.IsLoaded)
                        {
                            curShop.Shop_Product_Price.Load();
                        }
                        if (!oi.photoInfo.IsLoaded)
                        {
                            oi.photoInfo.Load();
                        }
                        if (!oi.Tb_OrderBagReference.IsLoaded)
                        {
                            oi.Tb_OrderBagReference.Load();
                        }
                        if (!oi.WorkOrderFlowList.IsLoaded)
                        {
                            oi.WorkOrderFlowList.Load();
                             oi.WorkOrderFlowList.ToList().ForEach(w=>w.tb_TechReference.Load());
                        }
                        if (oi.WorkOrderFlowList.FirstOrDefault(w => w.tb_Tech.TechType == 4) != null)
                        {
                            continue;
                        }
                        string orderBagName = oi.Tb_OrderBag.BagName.Split('_')[0];

                        #endregion

                        Bill_Detail bd = new Bill_Detail() { OiRemark = oi.Remark, OrderInfoCode = oi.OrderProductCode, OrderProductName = oi.OrderProductName, CtmName = oi.CtmName, IsCheckOut = false };
                        Bill_Detail_Info dbinfo = new Bill_Detail_Info() { BillDetailId = Bill_Detail_Id, Remark = oi.Remark, OrderInfoCode = oi.OrderProductId.ToString(), OrderProductName = oi.OrderProductName, CtmName = oi.CtmName, OrderBagName = orderBagName };
                        Bill_Detail_Id++;
                        dbinfo.ListDetail_Detail = new List<Bill_Detail_Detail_Info>();



                        orderInfoPrice = BillBLL.GetOrderPrice(curShop, oi, dataBase, bd);

                        ConvertOrderDetailaToViewModel(bd, curShop, dbinfo);


                        #region 如果产品满足财务信息，则可以找印帐单，并判断登陆者的权限在“在余额不足”情况下是否可以打帐单

                        #region //对帐户金额的操作
                        ShopBlanceCrushRecord br;
                        switch (curShop.CheckOutType)
                        {
                            case 0://预付款用户
                            case 2://现结用户
                            case 5://先结
                                #region


                                curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                if (curShop.OrderBalance < 0)
                                {
                                    curShop.OrderBalance = 0;
                                }


                                if (curShop.Balance < (decimal)orderInfoPrice)
                                {
                                    //如果余额不足，就判断是否有权限可打印此帐单
                                    if (hasForcibePrint)//可以强打
                                    {
                                        sb.Status = (int)ShopBillStatus.UnCheckOut;
                                        curShop.Balance -= (decimal)orderInfoPrice;
                                        //向商户帐户记录表添加记录
                                        br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                        dataBase.AddToShopBlanceCrushRecord(br);
                                    }
                                    else
                                    {
                                        oi.status = (int)OrderInfoStatus.WaitPay;
                                        curShop.OrderBalance += oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;

                                        DonedOrderProudctId.Remove(oi.OrderProductId);
                                    }
                                }
                                else
                                {

                                    bd.IsCheckOut = true;
                                    curShop.Balance -= (decimal)orderInfoPrice;

                                    //向商户帐户记录表添加记录
                                    br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                    dataBase.AddToShopBlanceCrushRecord(br);
                                }

                                //检查是否需要报警
                                if (curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                {
                                    BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);
                                }
                                #endregion
                                break;
                            case 1://信用额度用户
                            case 3://结帐日用户
                            case 4://结单日与信用额度用户
                            case 6://代收款
                                #region
                                curShop.OrderBalance -= oi.PrePriceCount == null ? 0 : (decimal)oi.PrePriceCount;
                                if (curShop.OrderBalance < 0)
                                {
                                    curShop.OrderBalance = 0;
                                }
                                curShop.Balance -= (decimal)orderInfoPrice;

                                if (curShop.CheckOutType == 1)//信用额度用户
                                {
                                    if (curShop.CreditLimit + curShop.Balance - curShop.OrderBalance <= curShop.AlarmLimit)
                                    {
                                        BillBLL.InsertAccountAlarmMsg("余额小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);

                                    }
                                }
                                else
                                {
                                    int days = new DateTime(sb.CreateTime.Year, sb.CreateTime.Month, (int)curShop.OverDay).Subtract(sb.CreateTime).Days;
                                    if (days > 0 && days < curShop.AlarmDays)
                                    {
                                        BillBLL.InsertAccountAlarmMsg("距结帐日小于:" + curShop.AlarmLimit, "产品号：" + oi.OrderProductId + "产品金额：" + orderInfoPrice + "当前余额为：" + curShop.Balance, curShop, dataBase, sb.CreateTime);
                                    }
                                }

                                //向商户帐户记录表添加记录
                                br = new ShopBlanceCrushRecord() { Shop = curShop, CrushMoney = -(decimal)orderInfoPrice, CrushTime = sb.CreateTime, Operator = "系统", Overage = (decimal)curShop.Balance, Remark = "产品号：" + oi.OrderProductId + "系统自动冲抵帐单 ", Operation = (int)CountOperationType.DiChong };
                                dataBase.AddToShopBlanceCrushRecord(br);
                                sb.Status = (int)ShopBillStatus.UnCheckOut;
                                #endregion
                                break;
                            default:
                                break;
                        }

                        #endregion
                        sb.Bill_Detail.Add(bd);

                        dbinfo.BillDetailId = Bill_Detail_Id;
                        sbinfo.List_Detail.Add(dbinfo);
                        Bill_Detail_Id++;
                        Bill_Price += (double)orderInfoPrice;
                        oi.isCount = (int)orderinfoPerBill.Printed;//0为
                        dataBase.SaveChanges();
                        #endregion


                        //return sbinfo;

                        //记录帐单信息          
                        sb.Shop = curShop;
                        sb.TotalPrice = (decimal)Math.Round(Bill_Price, 4, MidpointRounding.ToEven);
                        sbinfo.Shop = new Shop_Info() { Address = curShop.address, ShopId = curShop.ShopId, ShopKeeper = curShop.shopKeeper, ShopName = curShop.shopName, Tel1 = curShop.Tel1, Tel2 = curShop.Tel2, QQ = curShop.QQ, IsNeedPrintUPrice = curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice, Salesman = curShop.Salesman, CreditLevel = curShop.CreditLevel == null ? 0 : (int)curShop.CreditLevel, IsAssignByCustom = curShop.IsAssignByCustom };
                        sbinfo.ShopBalance = (double)curShop.Balance;//指商户的总共欠款额度(包括本帐单)

                        //sbinfo.BillCount = Bill_Price;
                        sbinfo.BillCount = Math.Round(Bill_Price, 4, MidpointRounding.ToEven);
                        if (sb.Bill_Detail.Count(a => a.OrderInfoCode != "0") > 0)
                        {
                            if (sb.Bill_Detail.Count(b => !b.IsCheckOut) > 0)
                            {
                                sb.Status = (int)ShopBillStatus.UnCheckOut;
                            }
                            else
                            {
                                sb.Status = (int)ShopBillStatus.CheckedOut;
                            }
                            sb.ShopBalance = curShop.Balance ?? 0;
                            dataBase.AddToSHOP_Bill(sb);

                            dataBase.SaveChanges();

                        }
                        else
                        {
                            sbinfo = null;
                            sb = null;

                        }
                        if (sbinfo != null)
                        {
                            sbinfo.BillId = sb.BillId;
                            sbinfo.List_Detail = sbinfo.List_Detail.OrderBy(ld => ld.CtmName).ToList();//按客户名称排个序                       
                        }
                        rtnList.Add(sbinfo);
                    }
                    tran.Commit();
                }
                catch (Exception ex)
                {

                    tran.Rollback();
                    rtnList = new List<SHOP_Bill_Info>();
                }



                return rtnList;
            }
        }
        /// <summary>
        /// 将Bill_Detail转换为要打印的信息
        /// </summary>
        /// <param name="bd"></param>
        /// <param name="curShop"></param>
        /// <param name="bdInfo"></param>
        private static void ConvertOrderDetailaToViewModel(Bill_Detail bd, Shop curShop, Bill_Detail_Info bdInfo)
        {
            foreach (var bdd in bd.Bill_Detail_Detail.ToList())
            {
                bdInfo.ListDetail_Detail.Add(new Bill_Detail_Detail_Info()
                {
                    Area = bdd.Area,
                    Count = bdd.Count,
                    DetailName = bdd.DetailName,
                    Num = bdd.Num,
                    Spec = bdd.Spec,
                    Type = bdd.Type ?? 0,
                    UnitPrice = (bool)(curShop.IsNeedPrintUPrice == null ? false : (bool)curShop.IsNeedPrintUPrice) ? bdd.UnitPrice : 0,
                    Bill_Detail_DetailId = bdInfo.BillDetailId,
                    DetailRemark = bdd.DetailRemark
                });
            }
        }



    }
}
